package ufro.biblioteca.ws.servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ufro.biblioteca.Socio;
import ufro.biblioteca.ws.vologin.VOLogin;

/**
 * Servlet implementation class UsuariosServlet
 */
@WebServlet("/adminUsuarios.servlet")
public class UsuariosServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UsuariosServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		
		String accion = request.getParameter("accion");
		System.out.println("Accion : " + accion);
		
		List<Socio> lista = (List<Socio>) request.getSession().getAttribute("listaSocio");
		System.out.println("USUARIO");
		
		Socio socio=new Socio();
		socio.setNombre(request.getParameter("nombre"));
		socio.setDomicilio(request.getParameter("domicilio"));
		socio.setCorreoElectronico(request.getParameter("mail"));
		if(!request.getParameter("telefono").equals(""))
			socio.setTelefono(Integer.parseInt(request.getParameter("telefono")));
		else
			socio.setTelefono(0);
		if(request.getParameter("ID").length()>0)
			socio.setID(Integer.parseInt(request.getParameter("ID")));
		else
			socio.setID(0);
		
		if (accion.equals("guardar")) {
			lista.add(socio);
		} else if (accion.equals("actualizar")) {
			for (Socio obj : lista) {
				if (obj.getNombre().equals(socio.getNombre())) {
					obj.setDomicilio(socio.getDomicilio());
					obj.setCorreoElectronico(socio.getCorreoElectronico());
					obj.setTelefono(socio.getTelefono());
					obj.setID(socio.getID());
				}
			}
		} else if (accion.equals("eliminar")) {
			for(Socio obj:lista){
				if (obj.getNombre().equals(socio.getNombre())){
					lista.remove(obj);
					break;
				}
			}
		}
		response.sendRedirect("usuarios.jsp");
	}
}